package com.application.lucky.fragment.main;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.activity.GroupActivity;
import com.application.lucky.activity.PbChatActivity;
import com.application.lucky.activity.SystemMessageActivity;
import com.application.lucky.adapter.P2ConvsAdapter;
import com.application.lucky.bean.eventbean.FriendListEvent;
import com.application.lucky.bean.eventbean.GroupClearUnReadEvent;
import com.application.lucky.bean.eventbean.GroupShowEvent;
import com.application.lucky.bean.eventbean.GroupUnreadEvent;
import com.application.lucky.bean.eventbean.HomePointEvent;
import com.application.lucky.bean.jsonBean.GroupListbean;
import com.application.lucky.bean.jsonBean.NoticeMessageBean;
import com.application.lucky.bean.sqliteBean.LateContactBean;
import com.application.lucky.config.Config;
import com.application.lucky.gen.LateContactBeanDao;
import com.application.lucky.manager.GroupDataManager;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.UserRequest;
import com.application.lucky.request.nav.UrlManager;
import com.application.lucky.utils.ConnUtil;
import com.application.lucky.utils.Flog;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.popupwindow.HomeAddPop;
import com.application.lucky.widget.popupwindow.HomeSearchPop;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.ISharedPreKey;
import com.application.mylibrary.utils.LogUtils;
import com.application.mylibrary.utils.SharedPreferencesUtil;
import com.qunar.im.base.common.BackgroundExecutor;
import com.qunar.im.base.common.ConversitionType;
import com.qunar.im.base.module.IMMessage;
import com.qunar.im.base.module.RecentConversation;
import com.qunar.im.base.structs.EncryptMessageType;
import com.qunar.im.base.structs.MessageStatus;
import com.qunar.im.base.util.DataCenter;
import com.qunar.im.base.util.MessageUtils;
import com.qunar.im.core.services.QtalkNavicationService;
import com.qunar.im.protobuf.common.ProtoMessageOuterClass;
import com.qunar.im.ui.activity.CollectionActivity;
import com.qunar.im.ui.activity.QunarWebActvity;
import com.qunar.im.ui.activity.RobotChatActivity;
import com.qunar.im.ui.activity.RobotExtendChatActivity;
import com.qunar.im.ui.fragment.BaseFragment;
import com.qunar.im.ui.presenter.IChatingPanelPresenter;
import com.qunar.im.ui.presenter.IConversationsManagePresenter;
import com.qunar.im.ui.presenter.impl.ChatingPanelPresenter;
import com.qunar.im.ui.presenter.impl.PbConversationManagePresenter;
import com.qunar.im.ui.presenter.views.IConversationListView;
import com.qunar.im.ui.presenter.views.IRefreshConversation;
import com.qunar.im.ui.presenter.views.ITopMeesageView;
import com.qunar.im.ui.util.ProfileUtils;
import com.qunar.im.utils.ConnectionUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by zhao.liu on 2014/8/21.
 */
public class FragmentP2 extends BaseFragment implements IConversationListView, IRefreshConversation {
    private static final String TAG = "ConversationFragment";
    // 为每个菜单定义一个标识
    final int MENU1 = 0x111;
    final int MENU2 = 0x112;
    final int MENU3 = 0x113;
    final int MENU4 = 0x114;
    final int MENU5 = 0x115;
    final int MENU6 = 0X116;
    ListView list;
    View layout_message;
    TextView tv_notice;
    View header;

    View headerLayoutGroup;
    View headerLayoutGroup0;
    ImageView iv_group_0;
    TextView tv_group_title0;
    TextView tv_group_content0;
    TextView tv_group_tip_0;
    View headerLayoutGroup1;
    ImageView iv_group_1;
    TextView tv_group_title1;
    TextView tv_group_tip_1;
    TextView tv_group_content1;
    View headerLayoutGroup2;
    ImageView iv_group_2;
    TextView tv_group_title2;
    TextView tv_group_content2;
    TextView tv_group_tip_2;
    TextView tvEmpty;
    private boolean isFirstShow = true;
    IConversationsManagePresenter convPresenter;
    IChatingPanelPresenter panelPresenter;
    P2ConvsAdapter recentConvsAdapter;
    //    RVRecentConvsAdapter recentConvsAdapter;
    //    private boolean readAllConversations = true;
//    private ShakeEventHandler shakeEventHandler;
    private String XmppId;
    private String RealUserId;
    //    HandleConvEvent handleConvEvent = new HandleConvEvent();
//    IChatRoomManagePresenter chatRoomManagePresenter;
    private AlertDialog encryptDialog;
    private String currentJid;
    private boolean isOnlyUnRead = false;

    private RecentConversation mCurrentConv;
    private View kefu;
    private volatile long insertTime = 0L;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getArguments() == null) {
            return;
        }

        isOnlyUnRead = getArguments().getBoolean("isOnlyUnRead");

    }

    private HomeSearchPop homeSearchPop;
    private HomeAddPop pop;
    TitlebarView titlBar;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.conversation_fragment, null, false);
        list = view.findViewById(R.id.list);
        layout_message = view.findViewById(R.id.layout_message);
        tv_notice = view.findViewById(R.id.tv_notice);
        tvEmpty = view.findViewById(R.id.empty);
        titlBar = view.findViewById(com.application.lucky.R.id.title_bar);
        titlBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {

            }

            @Override
            public void rightClick() {
                if (pop == null) {
                    pop = new HomeAddPop(getActivity());
                }
                pop.showAsDropDown(titlBar.getIv_right());
            }
        });
        titlBar.getIv_right2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (homeSearchPop == null) {
                    homeSearchPop = new HomeSearchPop(getContext());
                }
                homeSearchPop.show(titlBar);


            }
        });
        initViews();
        EventBusUtils.register(this);
        return view;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void transfer(FriendListEvent bean) {
        if (recentConvsAdapter != null) {
            recentConvsAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        currentJid = null;
        if (isLogin)
            convPresenter.showRecentConvs();
    }

    private boolean isLogin = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void islogin(LoginEvent loginEvent) {
        isLogin = true;
        convPresenter.showRecentConvs();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
        convPresenter.removeEvent();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        convPresenter = new PbConversationManagePresenter();
        convPresenter.setCoversationListView(this);
        panelPresenter = new ChatingPanelPresenter();
        convPresenter.showRecentConvs();
//        List<RecentConversation>  list = IMDatabaseManager.getInstance().getCurrentConversation();
//        setRecentConvList(list);
    }


    void initViews() {
        if (recentConvsAdapter == null) {
            recentConvsAdapter = new P2ConvsAdapter(getActivity());
        }
        list.setAdapter(recentConvsAdapter);
        list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
                int position = info.position - list.getHeaderViewsCount();
                if (position < 0) {
                    return;
                }
                RecentConversation rc = recentConvsAdapter.getItem(position);
                if (rc.getConversationType() == 1 || rc.getConversationType() == 0 || rc.getConversationType() == 3) {
                    if (rc.getTop() == 0) {
                        menu.add(0, MENU4, 0, R.string.atom_ui_menu_sticky_on_top);
                    } else {
                        menu.add(0, MENU4, 0, R.string.atom_ui_menu_remove_from_top);
                    }
                }
                //群才显示
                if (rc.getConversationType() == 1) {
                    if (rc.getRemind() == 0) {
                        menu.add(0, MENU6, 0, R.string.atom_ui_menu_mute_notification);
                    } else {
                        menu.add(0, MENU6, 0, R.string.atom_ui_menu_open_notification);
                    }
                }
                if (rc.getUnread_msg_cont() == 0) {
//                    menu.add(0, MENU3, 0, R.string.atom_ui_menu_mark_asunread);
                } else {
                    menu.add(0, MENU3, 0, R.string.atom_ui_menu_mark_asread);
                }
                menu.add(0, MENU2, 0, R.string.atom_ui_menu_delete_conversation);
            }


        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position - list.getHeaderViewsCount() < 0) {//防止点击header 数组越界crash
                    return;
                }
                recentConvClick(recentConvsAdapter.getItem(position - list.getHeaderViewsCount()), view);
            }
        });

        header = LayoutInflater.from(getActivity()).inflate(R.layout.view_contact_head_view, null);
        kefu = header.findViewById(R.id.rl_kefu);
        kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PbChatActivity.class);
                intent.putExtra(PbChatActivity.KEY_JID, Config.IMIdUtils.getIMUid(Config.KEFU_ID));
                intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, String.valueOf(ConversitionType.MSG_TYPE_CHAT));
                intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }

            }
        });
        header.findViewById(R.id.rl_system).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), SystemMessageActivity.class));
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }
            }
        });

        headerLayoutGroup = header.findViewById(R.id.layout_group);
        headerLayoutGroup0 = header.findViewById(R.id.layout_group_0);
        headerLayoutGroup1 = header.findViewById(R.id.layout_group_1);
        headerLayoutGroup2 = header.findViewById(R.id.layout_group_2);

        iv_group_0 = header.findViewById(R.id.iv_group_0);
        iv_group_1 = header.findViewById(R.id.iv_group_1);
        iv_group_2 = header.findViewById(R.id.iv_group_2);

        tv_group_title0 = header.findViewById(R.id.tv_group_title0);
        tv_group_title1 = header.findViewById(R.id.tv_group_title1);
        tv_group_title2 = header.findViewById(R.id.tv_group_title2);

        tv_group_content0 = header.findViewById(R.id.tv_group_content0);
        tv_group_content1 = header.findViewById(R.id.tv_group_content1);
        tv_group_content2 = header.findViewById(R.id.tv_group_content2);
        tv_group_tip_0 = header.findViewById(R.id.tv_group_tip_0);
        tv_group_tip_1 = header.findViewById(R.id.tv_group_tip_1);
        tv_group_tip_2 = header.findViewById(R.id.tv_group_tip_2);

        headerLayoutGroup.setVisibility(View.GONE);

//        if(getActivity() instanceof TabMainActivity){//未读消息的activity不展示搜索header
        list.addHeaderView(header);
//        }

        loadNotice();
        loadGroupConversation();
        loadLateData();
    }

    private void loadNotice() {
        new UserRequest().getNotice(new CallBackEx<NoticeMessageBean>() {
            @Override
            public void onSuccess(NoticeMessageBean response) {
                Flog.d(TAG, "loadNotice response:" + response);
                if (response != null && response.dataInfo != null && !TextUtils.isEmpty(response.dataInfo.content)) {
                    tv_notice.setText(response.dataInfo.content + "              " + response.dataInfo.content);
                    tv_notice.setSelected(true);
                }
            }

            @Override
            public void onFailed(int code) {
                Flog.d(TAG, "loadNotice code:" + code);
            }
        });
    }


    void recentConvClick(final RecentConversation item, View view) {
//        readAllConversations = true;
        Intent intent = null;
        switch (item.getConversationType()) {

            case ConversitionType.MSG_TYPE_COLLECTION:
                intent = new Intent(getContext(), CollectionActivity.class);
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }
                break;
            case ConversitionType.MSG_TYPE_CONSULT:
            case ConversitionType.MSG_TYPE_CONSULT_SERVER:
            case ConversitionType.MSG_TYPE_GROUP:
            case ConversitionType.MSG_TYPE_CHAT:

                intent = new Intent(getContext(), PbChatActivity.class);
                intent.putExtra(PbChatActivity.KEY_UNREAD_MSG_COUNT, item.getUnread_msg_cont());
                currentJid = item.getId();
                //设置jid 就是当前会话对象

                intent.putExtra(PbChatActivity.KEY_JID, item.getId());
                if (item.getConversationType() == 4) {

                } else if (item.getConversationType() == 5) {
                    intent.putExtra(PbChatActivity.KEY_REAL_JID, item.getRealUser());
                } else {
                    intent.putExtra(PbChatActivity.KEY_REAL_JID, item.getRealUser());
                }
                intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, item.getConversationType() + "");

                //设 置是否是群聊
                boolean isChatRoom = item.getConversationType() == ConversitionType.MSG_TYPE_GROUP;
                intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, isChatRoom);

                intent.putExtra(PbChatActivity.KEY_IS_REMIND, item.getRemind() == 0);

                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }
                break;
            case ConversitionType.MSG_TYPE_HEADLINE://qtalk的系统通知消息
                intent = new Intent(getContext(), RobotExtendChatActivity.class);
                intent.putExtra(PbChatActivity.KEY_JID, item.getId());
                //设置真实id
                intent.putExtra(PbChatActivity.KEY_REAL_JID, item.getRealUser());
                //设置是否是群聊
                intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);

                intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, item.getConversationType() + "");
                intent.putExtra(PbChatActivity.KEY_UNREAD_MSG_COUNT, item.getUnread_msg_cont());
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }
                break;
            case ConversitionType.MSG_TYPE_SUBSCRIPT://qchat的系统通知公告抢单消息 和 qtalk的订阅号消息
                if (item.getId().contains("rbt-qiangdan")) {//qchat抢单消息、众包消息
                    intent = new Intent(getContext(), QunarWebActvity.class);
                    intent.setData(Uri.parse(QtalkNavicationService.getInstance().getqGrabOrder()));
                    intent.putExtra(QunarWebActvity.IS_HIDE_BAR, true);
                    startActivity(intent);
                    if (getActivity() != null) {
                        getActivity().overridePendingTransition(0, 0);
                    }
                    //抢单消息 特殊处理 点击后 设置成已读
                    ConnectionUtil.getInstance().sendSingleAllRead(item.getId(), item.getId(), MessageStatus.STATUS_SINGLE_READED + "");
                } else if (item.getId().contains("rbt-system") || item.getId().contains("rbt-notice")) {//qchat的系统通知消息
                    intent = new Intent(getContext(), RobotExtendChatActivity.class);
                    intent.putExtra(PbChatActivity.KEY_JID, item.getId());
                    //设置真实id
                    intent.putExtra(PbChatActivity.KEY_REAL_JID, item.getRealUser());
                    //设置是否是群聊
                    intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);

                    intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, item.getConversationType() + "");
                    intent.putExtra(PbChatActivity.KEY_UNREAD_MSG_COUNT, item.getUnread_msg_cont());
                    startActivity(intent);
                    if (getActivity() != null) {
                        getActivity().overridePendingTransition(0, 0);
                    }
                } else {
                    intent = new Intent(getContext(), RobotChatActivity.class);
                    intent.putExtra(RobotChatActivity.ROBOT_ID_EXTRA, item.getId());
                    intent.putExtra(PbChatActivity.KEY_JID, item.getId());
                    //设置真实id
                    intent.putExtra(PbChatActivity.KEY_REAL_JID, item.getRealUser());
                    intent.putExtra(PbChatActivity.KEY_UNREAD_MSG_COUNT, item.getUnread_msg_cont());
                    startActivity(intent);
                    if (getActivity() != null) {
                        getActivity().overridePendingTransition(0, 0);
                    }
                }
                break;
            case ConversitionType.MSG_TYPE_FRIENDS_REQUEST:
                break;
            default:
                break;
        }

    }

    @Override
    public void setRecentConvList(final List<RecentConversation> convers) {
        super.getHandler().post(new Runnable() {
            @Override
            public void run() {
                EventBusUtils.post(new HomePointEvent(HomePointEvent.TAB_message));
                if (recentConvsAdapter != null) {
                    List<RecentConversation> dd = new ArrayList<>();
                    for (RecentConversation conversation : convers) {
                        if (!Config.IMIdUtils.isKefu(conversation.getId())) {
                            dd.add(conversation);
                        }
                    }
                    recentConvsAdapter.setRecentConversationList(dd);
                    insertLateContactDB(dd);
                }
            }
        });
    }

    @Override
    public void setRecentConvListCache(List<RecentConversation> convers) {
//        recentConvsAdapter
    }

    @Override
    public String getXmppId() {
        return XmppId;
    }

    @Override
    public String getRealUserId() {
        return RealUserId;
    }

    @Override
    public Context getContext() {
        return getActivity().getApplicationContext();
    }

    @Override
    public boolean isOnlyUnRead() {
        return isOnlyUnRead;
    }

    @Override
    public void refresh() {
        getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (recentConvsAdapter != null)
                    recentConvsAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public boolean readAllConversations() {
        return false;
    }


    @Override
    public boolean onContextItemSelected(MenuItem mi) {
        AdapterView.AdapterContextMenuInfo menuInfo;
        menuInfo = (AdapterView.AdapterContextMenuInfo) mi.getMenuInfo();
        final RecentConversation rc = (RecentConversation) recentConvsAdapter.getItem(menuInfo.position - list.getHeaderViewsCount());
        XmppId = rc.getId();
        RealUserId = rc.getRealUser();
        mCurrentConv = rc;
        panelPresenter.setPanelView(new ITopMeesageView() {
            @Override
            public String getJid() {
                return rc.getId();
            }

            @Override
            public boolean getTop() {
                return rc.getTop() == 0;
            }

            @Override
            public boolean getReMind() {
                return rc.getRemind() == 0;
            }

            @Override
            public String getRJid() {
                return rc.getRealUser();
            }

            @Override
            public Context getContext() {
                return getActivity().getApplicationContext();
            }
        });
//        recentConvsAdapter.notifyItemChanged(menuInfo.position);
        switch (mi.getItemId()) {
            case MENU1:
                convPresenter.deleteChatRecord();
                break;
            case MENU2:
                convPresenter.deleteCoversation();
                break;
            case MENU5:
                BackgroundExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        convPresenter.allRead();
                    }
                });
                break;
            case MENU3:
                BackgroundExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        convPresenter.markReadById();
                    }
                });
                break;
            case MENU4:
                //设置置顶或者取消置顶
//                Toast.makeText(getActivity(),"尝试置顶",Toast.LENGTH_LONG);

                panelPresenter.setConversationTopOrCancel();
//                convPresenter.showRecentConvs(true);
                break;

            case MENU6:
                panelPresenter.setConversationReMindOrCancel();
                break;
        }

        return true;
    }

    //    private static int count;
    private int position;

    public void MoveToUnread() {
        if (recentConvsAdapter == null) return;
        int count = recentConvsAdapter.getCount();

        for (int i = position; i < count; i++) {
            RecentConversation rc = recentConvsAdapter.getItem(i);
            //逻辑是判断是否有未读,并且没有设置不提醒
            if (rc.getUnread_msg_cont() > 0 && rc.getRemind() != 1) {
                list.setSelection(i + list.getHeaderViewsCount());
//                list.scrollToPosition(i);

                position = i + 1;

                break;
            }
            if (i == count - 1) {
                position = 0;
            }

        }
    }

    public void moveToTop() {
        if (list != null) list.smoothScrollToPosition(0);
    }

    @Override
    public void refreshConversation() {
//        if (!InternDatas.existKey(Constants.SYS.DND_LIST)) {
//            ConversationManagePresenter.getInstance().loadDoNotDisturbList();
//        }
//        convPresenter.showRecentConvs();
    }

    @Override
    public void showDialog(String msg) {
        if (commonDialog != null && getActivity() != null && !getActivity().isFinishing()) {
            commonDialog.setMessage(msg);
            commonDialog.setTitle(R.string.atom_ui_common_prompt);
            commonDialog.setPositiveButton(R.string.atom_ui_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    commonDialog.dismiss();
                }
            });
            commonDialog.show();
        }
    }

    @Override
    public void parseEncryptMessage(final IMMessage message) {
        if (!message.getConversationID().equals(currentJid)) {
            getHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (message.isCarbon()) {
                        dismissEncryptDialog();
                        Toast.makeText(getActivity(), R.string.atom_ui_tip_deal_other_client, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (message.getMsgType() == EncryptMessageType.BEGIN)
                        showEncryptSessionDialog(message);
                    else if (message.getMsgType() == EncryptMessageType.CANCEL) {
                        dismissEncryptDialog();
                        Toast.makeText(getActivity(), R.string.atom_ui_tip_encryp_cancel, Toast.LENGTH_SHORT).show();
                    } else if (message.getMsgType() == EncryptMessageType.CLOSE) {
                        dismissEncryptDialog();
                        Toast.makeText(getActivity(), R.string.atom_ui_tip_close_encrypted, Toast.LENGTH_SHORT).show();
                        DataCenter.encryptUsers.remove(message.getConversationID());
                    }

                }
            });
        }
    }

    @Override
    public void showFileSharing() {
//        if(header != null && getActivity() != null && !getActivity().isFinishing()){
//            header.findViewById(R.id.atom_ui_home_pc_layout).setVisibility(View.VISIBLE);
//        }
    }

    @Override
    public void hidenFileSharing() {
//        if(header != null && getActivity() != null && !getActivity().isFinishing()){
//            header.findViewById(R.id.atom_ui_home_pc_layout).setVisibility(View.GONE);
//        }
    }

    @Override
    public void loginState(final boolean isLogin) {
        if (header != null && getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LogUtils.i("imsdk   出现问题" + isLogin);
                    TextView status = header.findViewById(R.id.atom_ui_un_connected);
                    if (isLogin) {
                        status.setVisibility(View.GONE);
                        layout_message.setVisibility(View.VISIBLE);
                        tv_notice.setSelected(true);
                    } else {
                        status.setVisibility(View.VISIBLE);
                        layout_message.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    @Override
    public RecentConversation getCurrentConv() {
        return mCurrentConv;
    }

    @Override
    public void CreadSession(Map<String, RecentConversation> sessionMap, List<RecentConversation> list, IMMessage message) {
        createSession(sessionMap, list, message);

    }

    public void createSession(Map<String, RecentConversation> sessionMap, List<RecentConversation> list, IMMessage message) {
        String conversationId = message.getConversationID();
        RecentConversation recentConversation = sessionMap.get(conversationId);
        if (recentConversation == null) {
            convPresenter.showRecentConvs();
            return;
        }
        int signaleType = message.getSignalType();
        if (signaleType == ProtoMessageOuterClass.SignalType.SignalTypeReadmark_VALUE) {//消息已读状态
            boolean isRead = MessageStatus.isExistStatus(message.getReadState(), MessageStatus.REMOTE_STATUS_CHAT_READED);
            if (recentConversation != null && isRead) {
                recentConversation.setUnread_msg_cont(0);
            }
        } else {
            int topCounts = ConnectionUtil.getInstance().querryConversationTopCount();
            if (message.getDirection() == IMMessage.DIRECTION_RECV) {
                int unReadCount = recentConversation.getUnread_msg_cont();
                recentConversation.setUnread_msg_cont(++unReadCount);
            }
            recentConversation.setLastFrom(message.getRealfrom());
            recentConversation.setLastMsgTime(message.getTime().getTime());
            recentConversation.setLastMsg(ConnectionUtil.getInstance().getLastMsg(message.getMsgType(), message.getBody()));

            list.remove(recentConversation);
            if (recentConversation.getTop() == 1) {//置顶排在第一个
                list.add(0, recentConversation);
            } else {
                list.add(topCounts, recentConversation);
            }
        }
        recentConvsAdapter.notifyDataSetChanged();

    }


    private void dismissEncryptDialog() {
        if (encryptDialog != null && encryptDialog.isShowing())
            encryptDialog.dismiss();
    }

    private void showEncryptSessionDialog(final IMMessage message) {
        if (getActivity().isFinishing()) return;
        dismissEncryptDialog();
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.atom_ui_dialog_encrypt_seesion, null, false);
        final TextView encrypt_text = (TextView) view.findViewById(R.id.encrypt_text);
        Button encrypt_button1 = (Button) view.findViewById(R.id.encrypt_button1);
        Button encrypt_button2 = (Button) view.findViewById(R.id.encrypt_button2);
        ProfileUtils.loadNickName(message.getConversationID(), true, new ProfileUtils.LoadNickNameCallback() {
            @Override
            public void finish(final String name) {
                if (!TextUtils.isEmpty(name))
                    getHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            encrypt_text.setText(name + getString(R.string.atom_ui_tip_request_encrypt));
                        }
                    });
            }
        });
        encrypt_button1.setText(R.string.atom_ui_btn_refuse_encrypt);
        encrypt_button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissEncryptDialog();
                sendRefuseEncryptMsg(message.getToID(), message.getConversationID());
            }
        });
        encrypt_button2.setText(R.string.atom_ui_btn_open_encrypt);
        encrypt_button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissEncryptDialog();
                Intent intent = new Intent(getActivity(), PbChatActivity.class);
                intent.putExtra(PbChatActivity.KEY_JID, message.getConversationID());
                intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);
                intent.putExtra(PbChatActivity.KEY_ENCRYPT_BODY, message.getBody());
                startActivity(intent);
                if (getActivity() != null) {
                    getActivity().overridePendingTransition(0, 0);
                }
            }
        });
        builder.setView(view);
        encryptDialog = builder.show();
        encryptDialog.setCanceledOnTouchOutside(false);
    }

    //发送加密信令消息
    public void sendRefuseEncryptMsg(String fromId, String toId) {
        IMMessage message = MessageUtils.generateSingleIMMessage(fromId, toId, null, null, null);
        message.setType(ConversitionType.MSG_TYPE_ENCRYPT);
        message.setBody(getString(R.string.atom_ui_body_refuse_encrypt));
        message.setMsgType(EncryptMessageType.REFUSE);
        message.setDirection(IMMessage.DIRECTION_MIDDLE);
        ConnectionUtil.getInstance().sendEncryptSignalMessage(message);
    }

    @Subscribe
    public void onGroupShow(GroupShowEvent groupShowEvent) {
        if (groupShowEvent == null || ConnUtil.isEmpty(GroupDataManager.getInstance().getDataInfo())) {
            return;
        }

        int openIndex = 0;
        final List<GroupListbean> dataInfo = GroupDataManager.getInstance().getDataInfo();
        for (int i = 0; i < dataInfo.size(); i++) {
            final GroupListbean itemBean = dataInfo.get(i);
            final String roomTypeId = itemBean.getRoomTypeId();
            final String roomTypeName = itemBean.getRoomTypeName();

            if (SharedPreferencesUtil.getBoolean(getContext(), ISharedPreKey.KEY_OPEN_GROUP + roomTypeId, false)) {
                if (openIndex == 0 && headerLayoutGroup0.getVisibility() != View.VISIBLE) {
                    headerLayoutGroup0.setVisibility(View.VISIBLE);
                    tv_group_title0.setText(itemBean.getRoomTypeName());
                    tv_group_content0.setText(itemBean.getRoomTypeDesc());
                    ProfileUtils.displayGravatarRoundedCornerByImageSrc(getContext(), UrlManager.getHeadPic(itemBean.getRoomTypePic()), iv_group_0);
                    headerLayoutGroup0.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startGroupPage(roomTypeName, roomTypeId);
                        }
                    });
                    tv_group_tip_0.setTag(roomTypeId);
                } else if (openIndex == 1 && headerLayoutGroup1.getVisibility() != View.VISIBLE) {
                    headerLayoutGroup1.setVisibility(View.VISIBLE);
                    tv_group_title1.setText(itemBean.getRoomTypeName());
                    tv_group_content1.setText(itemBean.getRoomTypeDesc());
                    ProfileUtils.displayGravatarRoundedCornerByImageSrc(getContext(), UrlManager.getHeadPic(itemBean.getRoomTypePic()), iv_group_1);

                    headerLayoutGroup1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startGroupPage(roomTypeName, roomTypeId);
                        }
                    });
                    tv_group_tip_1.setTag(roomTypeId);
                } else if (openIndex == 2 && headerLayoutGroup2.getVisibility() != View.VISIBLE) {
                    headerLayoutGroup2.setVisibility(View.VISIBLE);
                    tv_group_title2.setText(itemBean.getRoomTypeName());
                    tv_group_content2.setText(itemBean.getRoomTypeDesc());
                    ProfileUtils.displayGravatarRoundedCornerByImageSrc(getContext(), UrlManager.getHeadPic(itemBean.getRoomTypePic()), iv_group_2);

                    headerLayoutGroup2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startGroupPage(roomTypeName, roomTypeId);
                        }
                    });
                    tv_group_tip_2.setTag(roomTypeId);
                }
                openIndex++;
            }
        }

        headerLayoutGroup.setVisibility(openIndex > 0 ? View.VISIBLE : View.GONE);
    }

    private void startGroupPage(String roomName, String roomTypeId) {
        Intent intent = new Intent(getContext(), GroupActivity.class);
        intent.putExtra("name", roomName);
        intent.putExtra("id", roomTypeId + "");
        startActivity(intent);
        if (getActivity() != null) {
            getActivity().overridePendingTransition(0, 0);
        }
    }

    private void loadGroupConversation() {
        List<GroupListbean> listBean = Lucky.getApplication().getDaoSession().getGroupListbeanDao().loadAll();
        GroupDataManager.getInstance().setDataInfo(listBean);
        onGroupShow(new GroupShowEvent());
    }

    private void loadLateData() {
        List<LateContactBean> listbean = Lucky.getApplication().getDaoSession().getLateContactBeanDao().loadAll();
        Flog.d(TAG, "loadLateData listbean:" + listbean);
        if (ConnUtil.isEmpty(listbean)) {
            return;
        }

        List<RecentConversation> list = new ArrayList<>(listbean.size());
        for (LateContactBean item : listbean) {
            RecentConversation recentConversation = new RecentConversation();
            item.copyToRecentConversation(recentConversation);
            list.add(recentConversation);
        }
        setRecentConvList(list);
    }

    private void insertLateContactDB(List<RecentConversation> list) {
        if (ConnUtil.isEmpty(list) || recentConvsAdapter == null) {
            return;
        }

        final List<RecentConversation> insertList = new ArrayList<>();
        List<RecentConversation> viewList = recentConvsAdapter.getRecentConversationList();
        if (ConnUtil.isEmpty(viewList)) {
            insertList.addAll(list);
        } else {
            for (RecentConversation insertItem : list) {
                if (!viewList.contains(insertItem)) {
                    insertList.add(insertItem);
                }
            }
        }

        if (ConnUtil.isEmpty(insertList)) {
            List<LateContactBean> listbean = Lucky.getApplication().getDaoSession().getLateContactBeanDao().loadAll();
            if (ConnUtil.isEmpty(listbean) && ConnUtil.isNotEmpty(list)) {
                insertList.addAll(list);
            } else {
                return;
            }
        }

        Observable observable = Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter emitter) {
                try {
                    if (ConnUtil.isEmpty(insertList)) {
                        return;
                    }

                    // 两次插入在500毫秒之内，不插入
                    if (insertTime != 0L && System.currentTimeMillis() - insertTime < 500L) {
                        return;
                    }
                    insertTime = System.currentTimeMillis();
                    Lucky.getApplication().getDb().beginTransaction();
                    for (RecentConversation insert : insertList) {
                        final LateContactBean bean = new LateContactBean();
                        bean.setRemind(insert.getRemind());
                        bean.setConversationType(insert.getConversationType());
                        bean.setUnread_msg_cont(insert.getUnread_msg_cont());
                        bean.setRealUser(insert.getRealUser());
                        bean.setId(insert.getId());
                        bean.setLastFrom(insert.getLastFrom());
                        bean.setMsgType(String.valueOf(insert.getMsgType()));
                        bean.setLastMsgTime(insert.getLastMsgTime());
                        bean.setLastMsg(insert.getLastMsg());
                        bean.setLastState(insert.getLastState());

                        LateContactBeanDao lateContactBeanDao = Lucky.getApplication().getDaoSession().getLateContactBeanDao();
                        lateContactBeanDao.insertOrReplace(bean);
                    }
                    Lucky.getApplication().getDb().setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Lucky.getApplication().getDb().endTransaction();
                }
            }
        });
        observable.subscribeOn(Schedulers.io()).subscribe();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateGroupUnread(GroupUnreadEvent event) {
        if (event == null) {
            return;
        }

        Object tip0 = tv_group_tip_0.getTag();
        if (tip0 instanceof String) {
            if (TextUtils.equals((String) tip0, event.groupID)) {
                if (event.count > 0) {
                    tv_group_tip_0.setText(event.count + "");
                    tv_group_tip_0.setVisibility(View.VISIBLE);
                } else {
                    tv_group_tip_0.setVisibility(View.INVISIBLE);
                }
                return;
            }
        }

        Object tip1 = tv_group_tip_1.getTag();
        if (tip1 instanceof String) {
            if (TextUtils.equals((String) tip1, event.groupID)) {
                if (event.count > 0) {
                    tv_group_tip_1.setText(event.count + "");
                    tv_group_tip_1.setVisibility(View.VISIBLE);
                } else {
                    tv_group_tip_1.setVisibility(View.INVISIBLE);
                }
                return;
            }
        }

        Object tip2 = tv_group_tip_2.getTag();
        if (tip2 instanceof String) {
            if (TextUtils.equals((String) tip2, event.groupID)) {
                if (event.count > 0) {
                    tv_group_tip_2.setText(event.count + "");
                    tv_group_tip_2.setVisibility(View.VISIBLE);
                } else {
                    tv_group_tip_2.setVisibility(View.INVISIBLE);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void clearGroupUnread(GroupClearUnReadEvent event) {
        if (event == null) {
            return;
        }

        Object tip0 = tv_group_tip_0.getTag();
        if (tip0 instanceof String) {
            if (TextUtils.equals((String) tip0, event.groupID)) {
                tv_group_tip_0.setVisibility(View.INVISIBLE);
                return;
            }
        }

        Object tip1 = tv_group_tip_1.getTag();
        if (tip1 instanceof String) {
            if (TextUtils.equals((String) tip1, event.groupID)) {
                tv_group_tip_1.setVisibility(View.INVISIBLE);
                return;
            }
        }

        Object tip2 = tv_group_tip_2.getTag();
        if (tip2 instanceof String) {
            if (TextUtils.equals((String) tip2, event.groupID)) {
                tv_group_tip_2.setVisibility(View.INVISIBLE);
            }
        }
    }
}

